import React from 'react';
import update from 'immutability-helper';

class Builder extends React.Component {

  /* 移动项 */
  moveItem = (id, atIndex, item = {}) => {
    let { card, index } = this.findItem(id);
    const { dropItem } = this.state;
    const newArr = [...dropItem];
    if (!card && index === -1) {
      card = item;
      card.hidden = true;
      index = card.originalIndex;
      newArr.push(card);
    }
    this.isMoving = true;
    this.atIndex = atIndex;
    this.changeAddStatus(false);
    this.setState(
      update({ dropItem: newArr }, {
        dropItem: {
          $splice: [[index, 1], [atIndex, 0, card]],
        },
      }),
    );
  }

  /* 查找 */
  findItem = (id) => {
    const { dropItem } = this.state;
    const card = dropItem.filter(c => c.id === id)[0];
    return {
      card,
      index: dropItem.indexOf(card),
    };
  }

  /* 放下 */
  handleItemDrop = (item) => {
    const { id } = item;
    const { dropItem } = this.state;
    const newArr = [...dropItem];
    this.isMoving = false;
    let { card, index } = this.findItem(id);
    if (!card && index === -1) {
      card = item;
      index = card.originalIndex;
      this.atIndex = card.originalIndex;
      newArr.push(card);
    }
    card.hidden = false;
    this.setState(
      update({ dropItem: newArr, selectedItem: { ...card, ...item } }, {
        dropItem: {
          $splice: [[index, 1], [this.atIndex || index, 0, { ...card, ...item }]],
        },
      }),
    );

    // 防止轻拖表单后出现在上一个atIndex的位置
    this.atIndex = undefined
  }

  /* 移除 */
  handleDelItem = (item) => {
    setTimeout(() => {
      const { dropItem, selectedItem } = this.state;
      const { index } = this.findItem(item.id);
      let newselectedItem = selectedItem;
      if (selectedItem.id === item.id) {
        newselectedItem = {};
      }
      if (index !== -1) {
        const newArr = [...dropItem];
        newArr.splice(index, 1);
        this.setState({ dropItem: newArr, selectedItem: newselectedItem });
      }
    }, 300);
  }

  /* 改变添加的状态 */
  changeAddStatus = (status = false) => {
    this.isAddItem = status;
    if (status) {
      this.moveDrop = false;
      // this.handleItemClick({});
    }
  }

  /* 控件项 点击 */
  handleItemClick = (item) => {
    const { selectedItem } = this.state;
    this.isMoving = false;
    if (selectedItem.id === item.id) return;
    this.setState({ selectedItem: item })
  }

  /* 项 改变 */
  handleItemChange = (item) => {
    const { card, index } = this.findItem(item.id);
    const { dropItem } = this.state;
    const newArr = [...dropItem];
    if (!card && index === -1) {
      return;
    }
    this.setState(
      update({ dropItem: newArr, selectedItem: item }, {
        dropItem: {
          $splice: [[index, 1], [index, 0, { ...card, ...item }]],
        },
      }),
    );
  }

  /* 画布 点击处理 */
  showPageConfig = () => {
    this.setState({ selectedItem: {} });
  }

}
export default Builder;